package com.zhglxt.activiti.controller;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zhglxt.activiti.entity.ModelEntityDto;
import com.zhglxt.activiti.service.ActModelService;
import com.zhglxt.common.annotation.Log;
import com.zhglxt.common.config.GlobalConfig;
import com.zhglxt.common.core.controller.BaseController;
import com.zhglxt.common.core.entity.AjaxResult;
import com.zhglxt.common.core.page.TableDataInfo;
import com.zhglxt.common.enums.BusinessType;
import com.zhglxt.common.utils.WebUtil;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_DESCRIPTION;
import static org.activiti.editor.constants.ModelDataJsonConstants.MODEL_NAME;

/**
 * 模型管理 操作处理
 * 封装了模型的线上创建，修改，保存，部署，TODO 添加手动上传流程模型处理功能
 * @author liuwy
 */
@Controller
@RequestMapping("/activiti/model")
public class ActModelController extends BaseController {
    private String prefix = "activiti/model";

    @Autowired
    private ActModelService actModelService;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 跳转到模型列表页面
     * @return
     */
    @RequiresPermissions("activiti:model:view")
    @RequestMapping("/myModel")
    public String myModel() {
        logger.info("ActModelController的myModel方法：--requestMapping:/myModel");
        return prefix + "/modelList";
    }



    /**
     * 跳转到-新增模型表单页面
     */
    @GetMapping("/myAdd")
    public String myAdd() {
        logger.info("ActModelController的myAdd方法：--get:/myAdd");
        return prefix + "/modelAdd";
    }

    /**
     * 新增基本参数定义的空白模型，保存后等待编辑
     */
    @RequiresPermissions("activiti:model:add")
    @Log(title = "我的流程模型管理", businessType = BusinessType.INSERT)
    @RequestMapping("/myAddModle")
    @ResponseBody
    public AjaxResult myAddModle(HttpServletRequest request) {
        logger.info("ActModelController的myAddModle方法：--requestMapping:/myAdd");
        if (GlobalConfig.isDemoEnabled()) {
            return error("演示模式不允许本操作");
        }
        int msg = 0;
        Map<String, Object> paramMap = WebUtil.paramsToMap(request.getParameterMap());
        try {
            org.activiti.engine.repository.Model modelData = actModelService.create(paramMap);
            if (!modelData.getId().isEmpty()) {
                msg = 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建模型失败：", e);
        }
        AjaxResult ajaxResult = toAjax(msg);
        logger.info("创建模型结果：{}",ajaxResult);
        return ajaxResult;
    }

    /**
     * 返回模型的json数据
     * @param modelId
     * @return
     */
    @GetMapping("/{modelId}/json")
    @ResponseBody
    public ObjectNode getEditorJson(@PathVariable String modelId) {
        logger.info("ActModelController的getEditorJson方法：--get:/{modelId}/json");
        ObjectNode modelNode = actModelService.selectWrapModelById(modelId);
        return modelNode;
    }



    /**
     * 导入stencil配置文件
     * 读取classpath资源路径下的文件，返回
     * @return
     */
    @GetMapping(value = "/editor/stencilset", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String getStencilset() {
        logger.info("ActModelController的getStencilset方法：--get:/editor/stencilset");
        // 读取资源文件
        InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json");
        try {
            return IOUtils.toString(stencilsetStream, "utf-8");
        } catch (Exception e) {
            throw new ActivitiException("导入 stencil 文件出现错误", e);
        }
    }




    //===================================================================================================

    /**
     * 返回模型列表json数据
     * @param modelEntityDto
     * @return
     */
    @RequiresPermissions("activiti:model:list")
    @RequestMapping("/modelList")
    @ResponseBody
    public TableDataInfo list(ModelEntityDto modelEntityDto) {
        logger.info("ActModelController的list方法：--post:/list");
        return actModelService.selectModelList(modelEntityDto);
    }

    /**
     * 编辑模型,跳转重定向到模型的编辑页面，todo,重复
     * @param modelId
     * @return
     */
    @RequiresPermissions("activiti:model:edit")
    @GetMapping("/editModel/{id}")
    public String edit(@PathVariable("id") String modelId) {
        logger.info("ActModelController的edit方法：--get:/edit/{modelId}");
        return redirect("/modeler.html?modelId=" + modelId);
    }

    /**
     * 保存修改的模型，对修改后的流程模型保存请求的处理
     * @param modelId
     * @param name
     * @param description
     * @param json_xml
     * @param svg_xml
     * @throws IOException
     */
    @Log(title = "模型管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{modelId}/save")
    @ResponseBody
    public void save(@PathVariable String modelId, String name, String description, String json_xml,
                     String svg_xml) throws IOException {
        logger.info("ActModelController的save方法：");
        Model model = actModelService.selectModelById(modelId);

        /**
         * 更新模型的metaInfo
         */
        ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());
        modelJson.put(MODEL_NAME, name);
        modelJson.put(MODEL_DESCRIPTION, description);
        model.setMetaInfo(modelJson.toString());


        model.setName(name);
        /**
         * 更新模型信息
         */
        actModelService.update(model, json_xml, svg_xml);

    }

    /**
     * 导出模型请求处理
     * @param id
     * @param response
     */
    @Log(title = "导出指定模型", businessType = BusinessType.EXPORT)
    @RequiresPermissions("activiti:model:export")
    @RequestMapping("/export/{id}")
    public void exportToXml(@PathVariable("id") String id, HttpServletResponse response) {
        logger.info("ActModelController的exportToXml方法：--");
        try {
            Model modelData = actModelService.selectModelById(id);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            JsonNode editorNode = new ObjectMapper().readTree(actModelService.getModelEditorSource(modelData.getId()));
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
            byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel);

            ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
            IOUtils.copy(in, response.getOutputStream());
            String filename = bpmnModel.getMainProcess().getId() + ".bpmn20.xml";
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            response.flushBuffer();
        } catch (Exception e) {
            throw new ActivitiException("导出model的xml文件失败，模型ID=" + id, e);
        }
    }

    /**
     * 部署流程
     *
     * @return
     * @throws Exception
     */
    @Log(title = "发布流程", businessType = BusinessType.UPDATE)
    @RequiresPermissions("activiti:model:deploy")
    @RequestMapping("/myDeploy/{id}")
    @ResponseBody
    public AjaxResult myDeploy(@PathVariable("id") String modelId) {
        logger.info("部署流程：/myDeploy");
        if (GlobalConfig.isDemoEnabled()) {
            return error("演示模式不允许本操作");
        }

        System.out.println("要部署的流程模型ID是："+modelId);
        return actModelService.myDeployProcess(modelId);
    }

    /**
     * 删除模型请求操作处理
     * @param ids
     * @return
     */
    @Log(title = "删除模型", businessType = BusinessType.DELETE)
    @RequiresPermissions("activiti:model:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        if (GlobalConfig.isDemoEnabled()) {
            return error("演示模式不允许本操作");
        }

        return toAjax(actModelService.deleteModelIds(ids));
    }

}
